package cn.hcbycloud.code.controller;

import cn.hcbycloud.code.model.GenConfigEntity;
import cn.hcbycloud.code.model.TbDatabaseConfEntity;
import cn.hcbycloud.code.service.SysGeneratorService;
import cn.hcbycloud.common.core.vo.Result;
import cn.hcbycloud.common.mvc.annotation.IgnoreResponseAdvice;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * 代码生成器控制层
 *
 * @author gaoheng
 * 2019年7月27日下午10:13:53
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping
public class CodeGeneratorController {
    private final SysGeneratorService sysGeneratorService;
    /**
     * 获取指定数据库
     */
    @GetMapping(value = {"/databases"})
    public List<TbDatabaseConfEntity> getTable() {
        return sysGeneratorService.getDatabases();

    }

    /**
     * 获取指定数据库中表信息
     */
    @GetMapping(value = {"/databases/{id}/tables/{tableName}", "/databases/{id}/tables"})
    public Result<List<TableInfo>> getTableInfo(@PathVariable String id, @PathVariable(required = false) String tableName) {
        return Result.ok("获取" + id + "数据库中表信息", sysGeneratorService.getTableList(id, tableName));
    }

    /**
     * 生成代码
     * eg: http://127.0.0.1:9092/codegen/codes?dbId=uaa&packageName=cn.yibiao163&author=WangHui&moduleName=uaa&tablePrefix=&tableName=user_info
     */
    @SneakyThrows
    @IgnoreResponseAdvice
    @GetMapping("/codes")
    public void generatorCode(@Valid GenConfigEntity genConfig, HttpServletResponse response, BindingResult bindingResult) {
        byte[] data = sysGeneratorService.generatorCode(genConfig);
        response.reset();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genConfig.getTableName()));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }
}
